//如果没有登录就返回登录界面
$(function() {
    $(window).on("load", function() {
        let user = JSON.parse(sessionStorage.getItem("userInfo"))
        console.log(user);
        if (user == null || user == undefined) {
            alert("您还未登陆!请先登录!")
            location = "../html/login.html"
        }
    })
})

$(function() {
    $.ajax({
        url: "/cart/getCart",
        data: { uId: JSON.parse(sessionStorage.getItem("userInfo")).uId },
        headers: {
            token: localStorage.token
        }

    }).then(function(result) {
        let { data } = result;

        let strHtml = ``
        let price = 0
        let num = 0
        data.forEach(item => {
            price += parseInt(item.cTotal)
            num += parseInt(item.cNumber)
            strHtml += `
            <tr class="indent-tr xxShoppingCart" rowNo="0" style="height: 1.2em">
                    <td class="choose-btn">
                        <input type="checkbox" name="all" class="checkedAll" checked="checked" style="width: 18px;height: 18px;margin-left:16px">
                    </td>
                    <td class="indent-product-name">
                        <a target="_blank" hidefocus='true' href="/XP001-ProductInfo/Initial-DF614500.html?studentId=0" title="${item.cName}">
                            <div class="indent-product" data-pid=${item.pId} style="background-image: url(${item.cImg});"></div>
                        </a>
                    </td>
                    <td>
                        <a target="_blank" hidefocus='true' href="/XP001-ProductInfo/Initial-DF614500.html?studentId=0" title="${item.cName}">
                        ${item.cName}			           </a>
                    </td>

                    <td class="indent-color-size">
                        <p class="indent-color">${item.cColor}</p>
                        <p class="indent-color">尺码：${item.cSize}</p>
                    </td>
                    <td class="indent-unit">
                        <p class="new-unit"><small>￥</small><span>${item.cPrice}</span></p>
                    </td>
                    <td class="indent-num-td xNumber">
                        <div class="indent-num-box clearfix">
                            <div class="xSalesAction-NumberAdd num-reduce">-</div>
                            <input class="indent-num xSalesAction-NumberTxt" value=${item.cNumber}>
                            <div class="xSalesAction-NumberDec num-add" style="">+</div>
                        </div>
                    </td>
                    <td class="indent-sum-box">
                        <p class="indent-sum">
                            ￥<span>${item.cTotal}</span>
                        </p>
                    </td>
                    <td class="indent-del-box">
                        <p class="indent-del" data-target="#ComfirmDeleteAddr" data-cid=${item.cId}>删除</p>
                    </td>
                </tr>
            `
        });

        $(".addCarts").html(strHtml)
        $("#totalMoney").text(price + ".00")
        $("#totalNum").text(num + ".00")
        $("#selectNum").text(num + ".00")

    })
})

//删除
$(function() {
    // console.log(11);
    $(".addCarts").on("click", ".indent-del-box p", function() {
        let self = $(this)
        $.ajax({
            url: "/cart/delete",
            type: "post",
            data: {
                cId: $(this).data("cid")
            },
            headers: {
                token: localStorage.token
            }
        }).then(function(res) {
            if (res.code == 200) {
                self.parents("tr").remove()
            }

            //删除后重新渲染数据
            $.ajax({
                url: "/cart/getCart",
                data: { uId: JSON.parse(sessionStorage.getItem("userInfo")).uId },
                headers: {
                    token: localStorage.token
                }

            }).then(function(result) {
                let { data } = result;
                // console.log(123);
                let strHtml = ``
                let price = 0
                let num = 0
                data.forEach(item => {
                    price += parseInt(item.cTotal)
                    num += parseInt(item.cNumber)
                    strHtml += `
                    <tr class="indent-tr xxShoppingCart" rowNo="0" style="height: 1.2em">
                            <td class="choose-btn">
                                <input type="checkbox" name="all" class="checkedAll" checked="checked" style="width: 18px;height: 18px;margin-left:16px">
                            </td>
                            <td class="indent-product-name">
                                <a target="_blank" hidefocus='true' href="/XP001-ProductInfo/Initial-DF614500.html?studentId=0" title="${item.cName}">
                                    <div class="indent-product" data-pid=${item.pId} style="background-image: url(${item.cImg});"></div>
                                </a>
                            </td>
                            <td>
                                <a target="_blank" hidefocus='true' href="/XP001-ProductInfo/Initial-DF614500.html?studentId=0" title="${item.cName}">
                                ${item.cName}			           </a>
                            </td>
        
                            <td class="indent-color-size">
                                <p class="indent-color">${item.cColor}</p>
                                <p class="indent-color">尺码：${item.cSize}</p>
                            </td>
                            <td class="indent-unit">
                                <p class="new-unit"><small>￥</small><span>${item.cPrice}</span></p>
                            </td>
                            <td class="indent-num-td xNumber">
                                <div class="indent-num-box clearfix">
                                    <div class="xSalesAction-NumberAdd num-reduce">-</div>
                                    <input class="indent-num xSalesAction-NumberTxt" value=${item.cNumber}>
                                    <div class="xSalesAction-NumberDec num-add" style="">+</div>
                                </div>
                            </td>
                            <td class="indent-sum-box">
                                <p class="indent-sum">
                                    ￥<span>${item.cTotal}</span>
                                </p>
                            </td>
                            <td class="indent-del-box">
                                <p class="indent-del" data-target="#ComfirmDeleteAddr" data-cid=${item.cId}>删除</p>
                            </td>
                        </tr>
                    `
                });

                $(".addCarts").html(strHtml)
                $("#totalMoney").text(price + ".00")
                $("#totalNum").text(num + ".00")
                $("#selectNum").text(num + ".00")

            })
        })
    })
})


//购物车
// 全选反选
$(function() {


    // $(".addCarts").on("mousemove", ".checkedAll", function() {
    //     var listCart = $(".addCarts").children()
    //     console.log(listCart);
    // })



    $("#checked01").on("click", function() {
        if ($("#checked01").is(':checked')) {
            $(".checkedAll").each((index, item) => {
                $(item).prop("checked", true)
            });
        } else {
            $(".checkedAll").each((index, item) => {
                $(item).prop("checked", false)
            });
        }
    })
    $(".addCarts").on("click", ".checkedAll", function() {
        var list = $(this).parents(".addCarts").children()
        var num = 0;
        var arr = [];
        // console.log(list.children().eq(0).children().eq(0));

        for (var i = 0; i < list.length; i++) {
            arr.push(list.eq(i).children().eq(6).children().eq(0).children("span").text())
            if (list.eq(i).children().eq(0).children().eq(0).is(":checked")) {
                num++
            }
        }

        if (list.length == num) {
            $("#checked01").prop("checked", true)
        } else {
            $("#checked01").prop("checked", false)
        }

        // $("#totalNum").text(list.length)
        // $("#selectNum").text(num)


    })

    $(".addCarts").on("click", ".num-reduce", function() {
        var num = $(this).next().val()
        var zjNum = 0
        let dj = parseInt($(this).parents(".indent-num-td").prev().find("span").text())
        num--
        if (num <= 1) {
            num = 1
        }
        $(this).next().val(num)
        $(this).parents(".indent-num-td").next().find("span").text(dj * num)
        var le = $(this).parents(".addCarts").eq(0).children().length

        //ajax
        var uId = JSON.parse(sessionStorage.getItem("userInfo")).uId
        var pId = $(this).parent().parent().parent().children().eq(1).children().children().attr("data-pid")
        console.log(pId);
        $.ajax({
            url: "/cart/update",
            type: "post",
            data: {
                cNumber: num,
                uId: uId,
                pId: pId
            },
            headers: {
                token: localStorage.token
            }
        }).then(function(res) {
            // console.log(res);
            if (res.code == 200) {}
        })



        var zj = $(this).parents(".indent-num-td").next().find("span").text()
        for (var i = 0; i < le; i++) {
            zjNum += parseInt($(this).parents(".addCarts").eq(0).children().eq(i).find(".indent-sum span").text())
        }
        $(this).parents(".trol-content").next().find("#totalMoney").text(zjNum + ".00")


    })
    $(".addCarts").on("click", ".num-add", function() {
        var num = $(this).prev().val()
        var zjNum = 0
        console.log(num);
        num++
        $(this).prev().val(num)
        let dj = parseInt($(this).parents(".indent-num-td").prev().find("span").text())
        $(this).parents(".indent-num-td").next().find("span").text(dj * num)

        var le = $(this).parents(".addCarts").eq(0).children().length
        var zj = $(this).parents(".indent-num-td").next().find("span").text()
        console.log(zj);
        for (var i = 0; i < le; i++) {
            zjNum += parseInt($(this).parents(".addCarts").eq(0).children().eq(i).find(".indent-sum span").text())
        }
        $(this).parents(".trol-content").next().find("#totalMoney").text(zjNum + ".00")
    })


    //登录显示
    $(function() {
        var user = JSON.parse(sessionStorage.getItem("userInfo"));
        var strHtml = `欢迎会员${user.name}`
        $(".goubleColor-red").text(strHtml)
        $(".goubleColor-red").css({
            color: "red"
        })
    })

})

//勾选时改变金额
$(function() {
    $(".addCarts").on("click", ".checkedAll", function() {
        var isCheck = $(this).prop("checked")
        var le = $(".addCarts :checkbox").length
        var zj = 0;
        var hj = Number($("#totalMoney").text())

        if (isCheck) {
            for (var i = 0; i < le; i++) {
                // zj += parseInt($(".addCarts  .indent-sum>span").eq(i).text())
                if ($(".addCarts :checkbox").eq(i).prop("checked")) {
                    var xj = Number($(".addCarts :checkbox").eq(i).parent().parent().find(".indent-sum span").text())
                    zj += xj
                }
            }
            $("#totalMoney").text(zj + ".00")
        }
        if (!isCheck) {
            hj -= parseInt($(this).parent().parent().find(".indent-sum span").text())
            $("#totalMoney").text(hj + ".00")
        }
    })
    $(".choose-all-btn :checkbox").on("click", function() {
        var isCheck = $(this).prop("checked")
        var le = $(".addCarts :checkbox").length
        var zj = 0;
        var hj = Number($("#totalMoney").text())

        if (isCheck) {
            for (var i = 0; i < le; i++) {
                zj += parseInt($(".addCarts .indent-sum>span").eq(i).text())
            }
            $("#totalMoney").text(zj + ".00")
        }
        if (!isCheck) {
            $("#totalMoney").text("0.00")
        }

    })
})